package com.imooc.business;

import com.imooc.business.core.DataProcess;
import com.imooc.business.util.report.ReportUtil;
import com.imooc.module.collect.enums.PeriodEnum;
import com.imooc.module.collect.enums.RuleTypeEnum;
import com.imooc.module.collect.request.ParamsRequest;
import com.imooc.module.query.enums.TableType;
import com.imooc.module.query.request.HttpQueryDataRequest;
import com.imooc.module.query.request.QueryRequest;
import com.imooc.module.query.response.QueryDataResponse;
import com.imooc.module.reponse.DataResponse;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Tim
 * @Description: 查询报表业务
 * @Version 1.0
 */
@Service
public class QueryTableBusiness {

    private final DataProcess dataProcess;

    public QueryTableBusiness(DataProcess dataProcess) {
        this.dataProcess = dataProcess;
    }

    public QueryDataResponse query(HttpQueryDataRequest request){
        QueryRequest.QueryRequestBuilder requestBuilder = QueryRequest.builder();
        requestBuilder.businessId(request.getBusinessId())
                .requestGroupId(request.getRequestGroupId())
                .periodType(PeriodEnum.parse(request.getPeriodType()))
                .startTime(request.getStartTime())
                .endTime(request.getEndTime())
                .tableType(TableType.TABLE);

        QueryRequest queryRequest = requestBuilder.build();

        ParamsRequest paramsRequest = new ParamsRequest();
        paramsRequest.setQueryRequest(queryRequest);
        paramsRequest.setRuleTypeEnum(RuleTypeEnum.QUERY);

        DataResponse dataResponse = dataProcess.process(paramsRequest);
        return buildResponse(dataResponse, queryRequest);
    }

    private QueryDataResponse buildResponse(DataResponse dataResponse, QueryRequest queryRequest){
        DataResponse.Table dataResponseTable = dataResponse.getTable();
        List<QueryDataResponse.TableData> dataList = dataResponseTable.getDataList();
        String[] columns = dataResponseTable.getColumns();
        String[] columnsAddName = new String[columns.length+1];
        switch (queryRequest.getDimension()){
            case USER -> columnsAddName[0] = "用户";
            case GROUP -> columnsAddName[0] = "群组";
            case SCHOLL -> columnsAddName[0] = "学校";
        }
        for (int i=0; i<columns.length; i++) {
            columnsAddName[i+1] = columns[i];
        }
        QueryDataResponse response = new QueryDataResponse();
        QueryDataResponse.Table table = new QueryDataResponse.Table();
        table.setDatas(dataList);
        table.setColumns(columnsAddName);
        table.setSubTitle(ReportUtil.getEntryName(queryRequest.getPeriodType().getType(), queryRequest.getStartTime(), queryRequest.getEndTime()));

        response.setTable(table);
        return response;
    }
}
